/**
 * 工况特定输入参数表前端管理JS
 */

// API基础路径
let aapInputAPI_BASE = '/api/feibiao/aap/input';

// 初始化API路径
document.addEventListener('DOMContentLoaded', function() {
    if (typeof API_BASE !== 'undefined') {
        aapInputAPI_BASE = `${API_BASE}/feibiao/aap/input`;
    }
});

/**
 * 加载工况特定输入参数表列表
 */
function loadAapInputList(page = 0, size = 10, sort = 'id,asc') {
    currentPage = page;
    pageSize = size;
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';

    fetch(`${aapInputAPI_BASE}/list?page=${page}&size=${size}&sort=${sort}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderAapInputTable(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            mainContent.innerHTML = `<div class="error-container">加载失败: ${error.message}</div>`;
            showMessage('获取工况特定输入参数失败: ' + error.message, 'error');
        });
}

/**
 * 渲染工况特定输入参数表
 * @param {Object} data - 分页数据
 */
function renderAapInputTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">工况特定输入参数表</h2>
            <button class="btn btn-primary" onclick="showAapInputForm()">新增</button>
        </div>
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索...">
            <button class="search-btn" onclick="searchAapInput()">搜索</button>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>工况类型</th>
                    <th>启动电流(A)</th>
                    <th>转矩脉动(%)</th>
                    <th>温度变化梯度(℃/min)</th>
                    <th>轴承温升速率(℃/h)</th>
                    <th>冷却效率(%)</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id || ''}</td>
                    <td>${item.operatingMode || ''}</td>
                    <td>${item.startingCurrent || ''}</td>
                    <td>${item.torqueRipple || ''}</td>
                    <td>${item.thermalGradient || ''}</td>
                    <td>${item.bearingTempRiseRate || ''}</td>
                    <td>${item.coolingEfficiency || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewAapInput(${item.id})">查看</a>
                        <a href="javascript:void(0)" onclick="editAapInput(${item.id})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteAapInput(${item.id})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
    }
    html += `
            </tbody>
        </table>
    `;
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                </li>
        `;
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
            }
        }
        html += `
                <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    mainContent.innerHTML = html;
}

/**
 * 跳转到指定页码
 * @param {number} page - 页码
 */
function gotoPage(page) {
    currentPage = page;
    loadAapInputList();
}

/**
 * 搜索工况特定输入参数表
 */
function searchAapInput() {
    const keyword = document.getElementById('searchInput').value.trim();
    currentPage = 0;
    let url = `${aapInputAPI_BASE}/search?page=${currentPage}&size=${pageSize}`;
    if (keyword) {
        url += `&keyword=${encodeURIComponent(keyword)}`;
    }
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderAapInputTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

/**
 * 显示工况特定输入参数表表单(新增/编辑)
 * @param {Object} data - 已有数据(编辑时传入)
 */
function showAapInputForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = data !== null;
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}工况特定输入参数</h2>
            <button class="btn btn-default" onclick="loadAapInputList()">返回列表</button>
        </div>
        <form id="aapInputForm" class="data-form">
            ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
            <div class="form-group">
                <label for="operatingMode">工况类型 <span class="required">*</span></label>
                <select id="operatingMode" name="operatingMode" class="form-control" required>
                    <option value="">-- 请选择 --</option>
                    <option value="低速" ${isEdit && data.operatingMode === '低速' ? 'selected' : ''}>低速</option>
                    <option value="中速" ${isEdit && data.operatingMode === '中速' ? 'selected' : ''}>中速</option>
                    <option value="高速" ${isEdit && data.operatingMode === '高速' ? 'selected' : ''}>高速</option>
                </select>
            </div>
            <div class="form-group">
                <label for="startingCurrent">启动电流(A) <span class="required">*</span></label>
                <input type="number" id="startingCurrent" name="startingCurrent" class="form-control" step="0.01" value="${isEdit && data.startingCurrent ? data.startingCurrent : ''}" required>
            </div>
            <div class="form-group">
                <label for="torqueRipple">转矩脉动(%) <span class="required">*</span></label>
                <input type="number" id="torqueRipple" name="torqueRipple" class="form-control" step="0.01" value="${isEdit && data.torqueRipple ? data.torqueRipple : ''}" required>
            </div>
            <div class="form-group">
                <label for="freqVibration">振动频谱特征 <span class="required">*</span></label>
                <textarea id="freqVibration" name="freqVibration" class="form-control" required>${isEdit && data.freqVibration ? data.freqVibration : ''}</textarea>
            </div>
            <div class="form-group">
                <label for="thermalGradient">温度变化梯度(℃/min) <span class="required">*</span></label>
                <input type="number" id="thermalGradient" name="thermalGradient" class="form-control" step="0.01" value="${isEdit && data.thermalGradient ? data.thermalGradient : ''}" required>
            </div>
            <div class="form-group">
                <label for="bearingTempRiseRate">轴承温升速率(℃/h) <span class="required">*</span></label>
                <input type="number" id="bearingTempRiseRate" name="bearingTempRiseRate" class="form-control" step="0.01" value="${isEdit && data.bearingTempRiseRate ? data.bearingTempRiseRate : ''}" required>
            </div>
            <div class="form-group">
                <label for="coolingEfficiency">冷却效率(%) <span class="required">*</span></label>
                <input type="number" id="coolingEfficiency" name="coolingEfficiency" class="form-control" step="0.01" value="${isEdit && data.coolingEfficiency ? data.coolingEfficiency : ''}" required>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadAapInputList()">取消</button>
            </div>
        </form>
    `;
    mainContent.innerHTML = html;
    document.getElementById('aapInputForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveAapInput(this, isEdit);
    });
}

/**
 * 保存工况特定输入参数表数据
 * @param {HTMLFormElement} form - 表单元素
 * @param {boolean} isEdit - 是否为编辑模式
 */
function saveAapInput(form, isEdit) {
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    if (data.startingCurrent) data.startingCurrent = parseFloat(data.startingCurrent);
    if (data.torqueRipple) data.torqueRipple = parseFloat(data.torqueRipple);
    if (data.thermalGradient) data.thermalGradient = parseFloat(data.thermalGradient);
    if (data.bearingTempRiseRate) data.bearingTempRiseRate = parseFloat(data.bearingTempRiseRate);
    if (data.coolingEfficiency) data.coolingEfficiency = parseFloat(data.coolingEfficiency);
    const url = isEdit ? `${aapInputAPI_BASE}/${data.id}` : `${aapInputAPI_BASE}`;
    const method = isEdit ? 'PUT' : 'POST';
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        return response.json();
    })
    .then(result => {
        showMessage(`工况特定输入参数${isEdit ? '更新' : '添加'}成功!`, 'success');
        loadAapInputList();
    })
    .catch(error => {
        console.error('保存失败:', error);
        showMessage(`保存失败: ${error.message}`, 'error');
    });
}

/**
 * 查看工况特定输入参数表详情
 * @param {number} id - 记录ID
 */
function viewAapInput(id) {
    fetch(`${aapInputAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showAapInputDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 显示工况特定输入参数表详情
 * @param {Object} data - 详情数据
 */
function showAapInputDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">工况特定输入参数详情</h2>
            <button class="btn btn-default" onclick="loadAapInputList()">返回列表</button>
        </div>
        <div class="data-detail">
            <div class="detail-group">
                <label>ID:</label>
                <div>${data.id || '--'}</div>
            </div>
            <div class="detail-group">
                <label>工况类型:</label>
                <div>${data.operatingMode || '--'}</div>
            </div>
            <div class="detail-group">
                <label>启动电流(A):</label>
                <div>${data.startingCurrent || '--'}</div>
            </div>
            <div class="detail-group">
                <label>转矩脉动(%):</label>
                <div>${data.torqueRipple || '--'}</div>
            </div>
            <div class="detail-group">
                <label>振动频谱特征:</label>
                <div>${data.freqVibration || '--'}</div>
            </div>
            <div class="detail-group">
                <label>温度变化梯度(℃/min):</label>
                <div>${data.thermalGradient || '--'}</div>
            </div>
            <div class="detail-group">
                <label>轴承温升速率(℃/h):</label>
                <div>${data.bearingTempRiseRate || '--'}</div>
            </div>
            <div class="detail-group">
                <label>冷却效率(%):</label>
                <div>${data.coolingEfficiency || '--'}</div>
            </div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editAapInput(${data.id})">编辑</button>
                <button class="btn btn-danger" onclick="deleteAapInput(${data.id})">删除</button>
                <button class="btn btn-default" onclick="loadAapInputList()">返回</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

/**
 * 编辑工况特定输入参数表
 * @param {number} id - 记录ID
 */
function editAapInput(id) {
    fetch(`${aapInputAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showAapInputForm(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 删除工况特定输入参数表
 * @param {number} id - 记录ID
 */
function deleteAapInput(id) {
    if (!confirm('确定要删除这条记录吗？此操作不可恢复!')) {
        return;
    }
    fetch(`${aapInputAPI_BASE}/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        showMessage('删除成功!', 'success');
        loadAapInputList();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

/**
 * 显示消息提示
 * @param {string} msg - 消息内容
 * @param {string} type - 消息类型：success, error, warn, info
 */
function showMessage(msg, type) {
    // 检查是否有全局的 showMessage 函数
    if (typeof window.showMessage === 'function' && window.showMessage !== showMessage) {
        window.showMessage(msg, type);
    } else {
        // 如果没有全局函数，使用简单的 alert
        alert(msg);
    }
} 